﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Zws.Common;

namespace Zws.Frameworker.Middlewares
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                var env = context.RequestServices.GetService<IHostEnvironment>();
                if (!env.IsDevelopment())
                {
                    //构建响应
                    await context.Response.WriteAsJsonAsync(ApiResult<string>.ErrorResult(ex.Message));
                }
                else
                {
                    //构建响应
                    await context.Response.WriteAsJsonAsync(ApiResult<string>.ErrorResult(ex.ToString()));
                }

            }
        }
    }
}
